﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace peonwar
{
    public class AnimatedSprite : Sprite
    {
        // ---CONSTRUCTORS---
        public AnimatedSprite()
        {
            this.Index = 0;
            this.Play = true;
        }

        // Surcharge pour donner directement la taille du sprite a afficher (imgwidth, imgheight)
        // le nombre d'image -1 du sprite (index max) et la vitesse de l'animation
        public AnimatedSprite(Texture2D tex, Vector2 pos, int imgwidth, int imgheight, int indexmax, double animationspeed)
        {
            this.Texture = tex;
            this.Position = pos;
            this.Index = 0;
            this.Play = true;
            this.Imgwidth = imgwidth;
            this.Imgheight = imgheight;
            this.Indexmax = indexmax;
            this.Animationspeed = animationspeed;
            this.Effect = SpriteEffects.None;
            this.Offset = 0;
        }

        // ---PROPERTIES---
        // Taille du sprite UNITAIRE (pas la sheet) a afficher
        protected int Imgwidth { get; set; }

        protected int Imgheight { get; set; }

        // Decalage horizontal du sprite sur la texture
        protected int Offset;

        // index de l'image courante de l'animation
        public double Index { get; set; }

        // index maxi (nb d'image de la sheet -1 )
        protected int Indexmax { get; set; }

        // Vitesse de defilement des images
        protected double Animationspeed { get; set; }

        // Jouer l'animation
        public bool Play { get; set; }

        // METHODES
        public virtual void UpDate(GameTime gameTime)
        {
            // Si l'animation joue alors :
            if (Play)
            {
                // Tant que l'index n'a pas depasse l'index max on l'incremente l'index de l'animationspeed
                Index += Animationspeed;
                if (Index >= Indexmax + 1)
                    Index = 0;
            }
        }

        public override void Draw(SpriteBatch spriteBatch, Camera camera)
        {
            int c = 0;
            if (camera != null)
                c = camera.Position;

            // La "Position" est au centre du sprite
            int newindex = (int)Math.Floor(Index);
            Rectangle Desti = new Rectangle((int)Position.X - (Imgwidth / 2) - c, (int)Position.Y - Imgheight / 2, Imgwidth, Imgheight);
            Rectangle Source = new Rectangle((newindex * Imgwidth), 0, Imgwidth, Imgheight);
            spriteBatch.Draw(Texture, Desti, Source, Color.White, 0f, Vector2.Zero, Effect, 0f);
            
        }
    }
}